/*
 * Copyright 2014 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview  Additional runtime functions required for transpilation from
 * ES6 to ES5 of code generated by the Dart Dev Compiler.
 *
 * Note that DDC's output cannot currently be lowered to ES3 (heavy use of
 * getters or setters, including in the runtime), so these helpers make no
 * attempt of fallback behaviour when methods like Object.getPrototypeOf or
 * Object.getOwnPropertyDescriptor are undefined (unlike helpers in es6/*.js).
 */
'require base';

/**
 * Gets a property descriptor for a target instance, skipping its class
 * and walking up the super-classes hierarchy.
 *
 * @private
 * @param {!Object} target
 * @param {!string} name
 * @return {?}
 */
$jscomp.getSuperPropertyDescriptor_ = function(target, name) {
  var getPrototypeOf = Object.getPrototypeOf;
  var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  var cls = getPrototypeOf(target);
  while (cls != null) {
    cls = getPrototypeOf(cls);
    if (cls != null) {
      var desc = getOwnPropertyDescriptor(cls, name);
      if (desc != null) {
        return desc;
      }
    }
  }
  return undefined;
};

/**
 * Gets a property of a target instance using its super class getter or value,
 * or returns undefined if that property is not defined on any ancestor.
 *
 * @param {!Object} target
 * @param {!string} propertyName
 * @return {*}
 */
$jscomp.superGet = function(target, propertyName) {
  var desc = $jscomp.getSuperPropertyDescriptor_(target, propertyName);
  return desc && (desc.get ? desc.get.call(target) : desc.value);
};

/**
 * Sets a property on a target instance using its super setter if is defined
 * on any ancestor, or setting it as a simple property on the target otherwise.
 *
 * @template T
 * @param {!Object} target
 * @param {!string} propertyName
 * @param {T} value
 * @return {T}
 */
$jscomp.superSet = function(target, propertyName, value) {
  var desc = $jscomp.getSuperPropertyDescriptor_(target, propertyName);
  if (desc) {
    if (!desc.set) {
      throw new TypeError('No setter for super.' + propertyName);
    }
    desc.set.call(target, value);
  } else {
    target[propertyName] = value;
  }
  return value;
};
